const vscode = require('vscode');
const fs = require('fs').promises;
const path = require('path');
const chokidar = require('chokidar');
const { fileExistsAtPath, ensureDirectoryExists, readFileContent, writeFileContent } = require('../../utils/fs');
const { secondsToMs } = require('../../utils/time');
const { spawn } = require('child_process');
const { createSchema, ListToolsResultSchema, ExecuteToolResultSchema } = require('../../utils/mcpSchema');

// 导入MCP SDK
const { Client } = require('@modelcontextprotocol/sdk/client/index.js'); 
const { StdioClientTransport } = require('@modelcontextprotocol/sdk/client/stdio.js');
const { SSEClientTransport } = require('@modelcontextprotocol/sdk/client/sse.js');

// MCP超时设置
const DEFAULT_MCP_TIMEOUT_SECONDS = 60;
const MIN_MCP_TIMEOUT_SECONDS = 1;
const DEFAULT_REQUEST_TIMEOUT_MS = 30000;

// 默认服务器端口
const DEFAULT_PORT = 8123;

/**
 * MCP连接配置类型
 */
const ServerConfigTypes = {
    SSE: 'sse',
    STDIO: 'stdio',
    HTTP: 'http'
};

/**
 * 服务器配置验证
 * @param {Object} config - 服务器配置
 * @returns {Boolean} 配置是否有效
 */
function validateServerConfig(config) {
    if (!config) return false;
    
    // 根据传输类型验证
    if (config.transportType === ServerConfigTypes.SSE) {
        return !!config.url;
    } else if (config.transportType === ServerConfigTypes.STDIO) {
        return !!config.command;
    } else if (config.transportType === ServerConfigTypes.HTTP) {
        return !!config.url;
    }
    
    return false;
}

/**
 * 根据配置确定传输类型
 * @param {Object} config - 服务器配置
 * @returns {string} - 传输类型
 */
function determineTransportType(config) {
    if (config.transportType) {
        return config.transportType;
    }
    
    if (config.command) {
        return ServerConfigTypes.STDIO;
    }
    
    if (config.url) {
        if (config.url.includes('/stream') || config.url.includes('/sse')) {
            return ServerConfigTypes.SSE;
        }
        return ServerConfigTypes.HTTP;
    }
    
    return ServerConfigTypes.HTTP;
}

/**
 * MCP服务核心类，负责管理服务器连接
 */
class McpHub {
    constructor(
        getMcpServersPath,
        getSettingsDirectoryPath,
        postMessageToWebview,
        clientVersion
    ) {
        this.getMcpServersPath = getMcpServersPath;
        this.getSettingsDirectoryPath = getSettingsDirectoryPath;
        this.postMessageToWebview = postMessageToWebview;
        this.clientVersion = clientVersion || '1.0.0';
        this.disposables = [];
        this.settingsWatcher = undefined;
        this.fileWatchers = new Map();
        this.connections = [];
        this.isConnecting = false;
        
        // 初始化
        this.watchMcpSettingsFile();
        this.initializeMcpServers();
    }

    /**
     * 获取服务器列表
     */
    getServers() {
        return this.connections
            .map(conn => conn.server);
    }

    /**
     * 获取MCP设置文件路径
     */
    async getMcpSettingsFilePath() {
        const settingsDir = await this.getSettingsDirectoryPath();
        // 确保设置目录存在
        await ensureDirectoryExists(settingsDir);
        
        const mcpSettingsFilePath = path.join(settingsDir, "mcpSettings.json");
        const fileExists = await fileExistsAtPath(mcpSettingsFilePath);
        if (!fileExists) {
            await writeFileContent(
                mcpSettingsFilePath,
                `{
  "mcpServers": {
    
  }
}`
            );
        }
        return mcpSettingsFilePath;
    }

    /**
     * 读取并验证设置文件
     */
    async readAndValidateMcpSettingsFile() {
        try {
            const settingsPath = await this.getMcpSettingsFilePath();
            const content = await readFileContent(settingsPath);

            let config;

            // 解析JSON文件内容
            try {
                config = JSON.parse(content);
            } catch (error) {
                vscode.window.showErrorMessage(
                    "MCP设置格式无效。请确保您的设置遵循正确的JSON格式。"
                );
                return undefined;
            }

            // 初始化mcpServers字段（如果不存在）
            if (!config.mcpServers) {
                config.mcpServers = {};
            }

            return config;
        } catch (error) {
            console.error("读取MCP设置失败:", error);
            return undefined;
        }
    }

    /**
     * 监听设置文件变更
     */
    async watchMcpSettingsFile() {
        try {
            const settingsPath = await this.getMcpSettingsFilePath();
            console.log('监听MCP设置文件:', settingsPath);
            
            this.disposables.push(
                vscode.workspace.onDidSaveTextDocument(async (document) => {
                    if (document.uri.fsPath === settingsPath) {
                        console.log('MCP设置文件已更改');
                        const settings = await this.readAndValidateMcpSettingsFile();
                        if (settings) {
                            try {
                                vscode.window.showInformationMessage("正在更新MCP服务器...");
                                await this.updateServerConnections(settings.mcpServers);
                                vscode.window.showInformationMessage("MCP服务器已更新");
                            } catch (error) {
                                console.error("处理MCP设置更改失败:", error);
                            }
                        }
                    }
                })
            );
        } catch (error) {
            console.error('设置MCP设置文件监听失败:', error);
        }
    }

    /**
     * 初始化服务器
     */
    async initializeMcpServers() {
        const settings = await this.readAndValidateMcpSettingsFile();
        if (settings) {
            await this.updateServerConnections(settings.mcpServers);
        }
    }

    /**
     * 连接到服务器
     */
    async connectToServer(name, config) {
        // 移除现有连接
        this.connections = this.connections.filter((conn) => conn.server.name !== name);

        try {
            console.log(`尝试连接MCP服务器 ${name}...`, { config });
            
            // 创建一个临时服务器对象以显示连接状态
            const tempServer = {
                name,
                config: JSON.stringify(config),
                status: "connecting",
                disabled: config.disabled || false,
                error: "",
                tools: []
            };
            
            // 添加临时连接
            this.connections.push({
                server: tempServer,
                client: null,
                transport: null
            });
            
            // 通知WebView更新状态
            await this.notifyWebviewOfServerChanges();
            
            // 确定传输类型
            const transportType = determineTransportType(config);
            console.log(`服务器 ${name} 传输类型: ${transportType}`);
            
            // 如果服务器被禁用，仅保存配置，不建立连接
            if (config.disabled) {
                console.log(`服务器 ${name} 已禁用，不建立连接`);
                const connection = this.connections.find(conn => conn.server.name === name);
                if (connection) {
                    connection.server.status = "disabled";
                }
                await this.notifyWebviewOfServerChanges();
                return;
            }
            
            // 创建客户端
            const client = new Client(
                {
                    name: "VSCode MCP Client",
                    version: this.clientVersion
                },
                {
                    capabilities: {}
                }
            );
            
            // 创建传输
            let transport;
            
            if (transportType === ServerConfigTypes.SSE) {
                if (!config.url) {
                    throw new Error("SSE配置缺少URL");
                }
                
                const url = new URL(config.url);
                console.log(`创建SSE传输: ${url.toString()}`);
                transport = new SSEClientTransport(url);
                
            } else if (transportType === ServerConfigTypes.STDIO) {
                if (!config.command) {
                    throw new Error("STDIO配置缺少命令");
                }
                
                console.log(`创建STDIO传输: ${config.command}`, { args: config.args || [] });
                transport = new StdioClientTransport({
                    command: config.command,
                    args: config.args || [],
                    env: {
                        ...config.env,
                        ...(process.env.PATH ? { PATH: process.env.PATH } : {})
                    },
                    stderr: "pipe"  // 捕获stderr输出
                });
                
            } else if (transportType === ServerConfigTypes.HTTP) {
                if (!config.url) {
                    throw new Error("HTTP配置缺少URL");
                }
                
                console.log(`创建HTTP客户端: ${config.url}`);
                // 使用makeHttpRequest函数获取工具列表
                const connection = this.connections.find(conn => conn.server.name === name);
                if (connection) {
                    connection.server.status = "connected";
                    connection.server.error = "";
                    // 稍后我们会手动请求工具列表
                    await this.fetchToolsList(name, config.url);
                    await this.notifyWebviewOfServerChanges();
                    return;
                }
            } else {
                throw new Error(`不支持的传输类型: ${transportType}`);
            }
            
            // 设置错误处理
            transport.onerror = async (error) => {
                console.error(`传输错误 ${name}:`, error);
                const connection = this.connections.find((conn) => conn.server.name === name);
                if (connection) {
                    connection.server.status = "disconnected";
                    connection.server.error = error.message || '传输错误';
                }
                await this.notifyWebviewOfServerChanges();
            };
            
            // 设置关闭处理
            transport.onclose = async () => {
                console.log(`传输已关闭 ${name}`);
                const connection = this.connections.find((conn) => conn.server.name === name);
                if (connection) {
                    connection.server.status = "disconnected";
                }
                await this.notifyWebviewOfServerChanges();
            };
            
            // 查找连接
            const connection = this.connections.find(conn => conn.server.name === name);
            if (!connection) {
                throw new Error(`找不到连接 ${name}`);
            }
            
            // 设置连接对象
            connection.client = client;
            connection.transport = transport;
            
            // 对于STDIO，设置stderr监听
            if (transportType === ServerConfigTypes.STDIO) {
                await transport.start();
                
                // 安全地处理stderr - 只对StdioClientTransport处理
                const stdioTransport = transport;
                if (transportType === ServerConfigTypes.STDIO && 'stderr' in stdioTransport && stdioTransport.stderr) {
                    console.log(`为 ${name} 设置stderr监听`);
                    stdioTransport.stderr.on('data', (data) => {
                        const output = data.toString();
                        const isInfoLog = !/\berror\b/i.test(output);
                        
                        if (isInfoLog) {
                            console.log(`${name} 日志:`, output);
                        } else {
                            console.error(`${name} 错误:`, output);
                            // 附加错误信息
                            if (connection) {
                                connection.server.error = connection.server.error
                                    ? `${connection.server.error}\n${output}`
                                    : output;
                                    
                                // 如果已断开连接，通知WebView
                                if (connection.server.status === 'disconnected') {
                                    this.notifyWebviewOfServerChanges();
                                }
                            }
                        }
                    });
                }
                
                // 对于STDIO，需要跳过.connect()中的start()
                if (typeof transport.start === 'function') {
                    const originalStart = transport.start;
                    transport.start = async () => {};
                }
            }
            
            // 建立连接
            console.log(`建立连接到 ${name}...`);
            await client.connect(transport);
            console.log(`连接已建立到 ${name}`);
            
            // 更新服务器信息
            connection.server.status = "connected";
            connection.server.error = "";
            
            // 获取工具列表
            try {
                await this.fetchToolsFromClient(name, client);
            } catch (error) {
                console.error(`获取工具列表失败: ${name}`, error);
                connection.server.tools = [];
            }
            
            // 通知WebView
            await this.notifyWebviewOfServerChanges();
            
            // 设置文件监视
            if (transportType === ServerConfigTypes.STDIO && config.args) {
                this.setupFileWatcher(name, config);
            }
            
        } catch (error) {
            console.error(`连接到服务器失败: ${name}`, error);
            
            // 更新连接状态
            const connection = this.connections.find(conn => conn.server.name === name);
            if (connection) {
                connection.server.status = "disconnected";
                connection.server.error = error.message || "连接失败";
            }
            
            // 通知WebView
            await this.notifyWebviewOfServerChanges();
            
            throw error;
        }
    }

    /**
     * 从客户端获取工具列表
     */
    async fetchToolsFromClient(name, client) {
        console.log(`获取 ${name} 的工具列表...`);
        const connection = this.connections.find(conn => conn.server.name === name);
        if (!connection) {
            throw new Error(`找不到连接 ${name}`);
        }
        
        const response = await client.request(
            { method: "tools/list" },
            ListToolsResultSchema,  // 使用导入的schema对象
            { timeout: DEFAULT_REQUEST_TIMEOUT_MS }
        );
        
        // 保存工具列表
        if (response && response.tools) {
            console.log(`获取到 ${response.tools.length} 个工具:`, response.tools);
            
            // 获取自动批准设置
            const settingsPath = await this.getMcpSettingsFilePath();
            const content = await readFileContent(settingsPath);
            const config = JSON.parse(content);
            const autoApproveConfig = config.mcpServers[name]?.autoApprove || [];
            
            // 设置工具的autoApprove属性并保留所有原始工具信息
            connection.server.tools = response.tools.map(tool => ({
                ...tool, // 保留工具所有原始信息，包括参数架构
                autoApprove: autoApproveConfig.includes(tool.name)
            }));
            
            // 打印参数信息，用于调试
            for (const tool of connection.server.tools) {
                if (tool.parameters || tool.schema) {
                    console.log(`工具 ${tool.name} 包含参数信息:`, tool.inputSchema.properties || tool.schema.properties);
                }
            }
        } else {
            console.log(`未获取到工具列表，使用空列表`);
            connection.server.tools = [];
        }
    }
    
    /**
     * 通过HTTP请求获取工具列表
     */
    async fetchToolsList(name, url) {
        console.log(`通过HTTP获取 ${name} 的工具列表...`);
        const connection = this.connections.find(conn => conn.server.name === name);
        if (!connection) {
            throw new Error(`找不到连接 ${name}`);
        }

        try {
            const toolsUrl = url.endsWith('/') ? `${url}tools/list` : `${url}/tools/list`;
            console.log(`请求工具列表URL: ${toolsUrl}`);
            
            const response = await this.makeHttpRequest(toolsUrl, 'POST', {
                method: 'tools/list'
            });
            
            if (response && response.tools) {
                console.log(`HTTP获取到 ${response.tools.length} 个工具:`, response.tools);
                
                // 获取自动批准设置
                const settingsPath = await this.getMcpSettingsFilePath();
                const content = await readFileContent(settingsPath);
                const config = JSON.parse(content);
                const autoApproveConfig = config.mcpServers[name]?.autoApprove || [];
                
                // 设置工具的autoApprove属性并保留所有原始信息
                connection.server.tools = response.tools.map(tool => ({
                    ...tool, // 保留所有原始信息，包括参数架构
                    autoApprove: autoApproveConfig.includes(tool.name)
                }));
                
                // 打印参数信息，用于调试
                for (const tool of connection.server.tools) {
                    if (tool.parameters || tool.schema) {
                        console.log(`工具 ${tool.name} 包含参数信息:`, tool.parameters || tool.schema);
                    }
                }
            } else {
                console.log(`未获取到工具列表，使用空列表`);
                connection.server.tools = [];
            }
        } catch (error) {
            console.error(`通过HTTP获取工具列表失败: ${name}`, error);
            connection.server.tools = [];
            connection.server.error = `获取工具列表失败: ${error.message}`;
        }
    }
    
    /**
     * 发送HTTP请求
     */
    async makeHttpRequest(url, method, body) {
        console.log(`发送HTTP请求: ${method} ${url}`, body);
        
        const headers = {
            'Content-Type': 'application/json',
            'User-Agent': `VSCode-MCP-Client/${this.clientVersion}`
        };
        
        try {
            // 使用模块而非全局fetch
            const nodeFetch = require('node-fetch');
            const response = await nodeFetch(url, {
                method,
                headers,
                body: JSON.stringify(body),
                timeout: DEFAULT_REQUEST_TIMEOUT_MS
            });
            
            if (!response.ok) {
                throw new Error(`HTTP请求失败: ${response.status} ${response.statusText}`);
            }
            
            return await response.json();
        } catch (error) {
            console.error(`HTTP请求错误: ${url}`, error);
            throw error;
        }
    }
    
    /**
     * 发送STDIO请求
     */
    async makeStdioRequest(command, args, requestData) {
        console.log(`发送STDIO请求: ${command}`, args, requestData);
        
        return new Promise((resolve, reject) => {
            const { spawn } = require('child_process');
            const childProcess = spawn(command, args, {
                env: {
                    ...process.env,
                    PATH: process.env.PATH
                }
            });
            
            let stdout = '';
            let stderr = '';
            
            childProcess.stdout.on('data', (data) => {
                stdout += data.toString();
            });
            
            childProcess.stderr.on('data', (data) => {
                stderr += data.toString();
            });
            
            childProcess.on('close', (code) => {
                if (code !== 0) {
                    reject(new Error(`进程退出，代码 ${code}: ${stderr}`));
                    return;
                }
                
                try {
                    const response = JSON.parse(stdout);
                    resolve(response);
                } catch (error) {
                    reject(new Error(`解析响应失败: ${error.message}`));
                }
            });
            
            childProcess.on('error', (error) => {
                reject(error);
            });
            
            if (requestData) {
                childProcess.stdin.write(JSON.stringify(requestData));
                childProcess.stdin.end();
            }
        });
    }

    /**
     * 设置文件监视器
     */
    setupFileWatcher(name, config) {
        // 查找可能包含index.js的参数
        const filePath = config.args.find(arg => arg.includes('.js'));
        if (filePath) {
            try {
                console.log(`为 ${name} 设置文件监视: ${filePath}`);
                
                // 创建监视器
                const watcher = chokidar.watch(filePath, {
                    persistent: true,
                    ignoreInitial: true,
                    awaitWriteFinish: true
                });
                
                // 监听文件变化
                watcher.on('change', async () => {
                    console.log(`检测到文件变化: ${filePath}，正在重启 ${name}`);
                    await this.restartConnection(name);
                });
                
                // 保存监视器
                this.fileWatchers.set(name, watcher);
                
            } catch (error) {
                console.error(`设置文件监视失败: ${name}`, error);
            }
        }
    }
    
    /**
     * 移除所有文件监视器
     */
    removeAllFileWatchers() {
        console.log('移除所有文件监视器');
        for (const [name, watcher] of this.fileWatchers.entries()) {
            try {
                watcher.close();
            } catch (error) {
                console.error(`关闭文件监视器失败: ${name}`, error);
            }
        }
        this.fileWatchers.clear();
    }
    
    /**
     * 删除连接
     */
    async deleteConnection(name) {
        console.log(`删除连接: ${name}`);
        const connection = this.connections.find(conn => conn.server.name === name);
        if (connection) {
            try {
                // 关闭传输
                if (connection.transport) {
                    await connection.transport.close();
                }
                
                // 关闭客户端
                if (connection.client) {
                    await connection.client.close();
                }
                
                // 移除文件监视器
                const watcher = this.fileWatchers.get(name);
                if (watcher) {
                    await watcher.close();
                    this.fileWatchers.delete(name);
                }
            } catch (error) {
                console.error(`关闭连接失败: ${name}`, error);
            }
            
            // 从连接列表中移除
            this.connections = this.connections.filter(conn => conn.server.name !== name);
        }
    }
    
    /**
     * 重启连接
     */
    async restartConnection(serverName) {
        if (this.isConnecting) {
            console.log(`已有连接正在进行，不重启 ${serverName}`);
            return;
        }
        
        this.isConnecting = true;
        
        try {
            console.log(`重启连接: ${serverName}`);
            
            // 获取现有连接和配置
            const connection = this.connections.find(conn => conn.server.name === serverName);
            if (!connection) {
                throw new Error(`找不到服务器: ${serverName}`);
            }
            
            // 获取配置
            const config = JSON.parse(connection.server.config);
            
            // 更新状态
            connection.server.status = "connecting";
            connection.server.error = "";
            
            // 通知WebView
            await this.notifyWebviewOfServerChanges();
            
            // 添加人工延迟，让UI更新
            await new Promise(resolve => setTimeout(resolve, 500));
            
            // 删除旧连接并创建新连接
            await this.deleteConnection(serverName);
            await this.connectToServer(serverName, config);
            
            vscode.window.showInformationMessage(`已重启 ${serverName} MCP服务器`);
            
        } catch (error) {
            console.error(`重启连接失败: ${serverName}`, error);
            vscode.window.showErrorMessage(`重启MCP服务器失败: ${serverName}`);
        } finally {
            this.isConnecting = false;
        }
    }
    
    /**
     * 更新服务器连接
     */
    async updateServerConnections(newServers) {
        if (this.isConnecting) {
            console.log('已有更新在进行，跳过更新');
            return;
        }
        
        this.isConnecting = true;
        this.removeAllFileWatchers();
        
        try {
            console.log('更新服务器连接...');
            
            // 获取当前连接的服务器名称
            const currentNames = this.connections.map(conn => conn.server.name);
            
            // 获取新配置的服务器名称
            const newNames = Object.keys(newServers);
            
            console.log('当前服务器:', currentNames);
            console.log('新服务器:', newNames);
            
            // 删除已移除的服务器
            for (const name of currentNames) {
                if (!newNames.includes(name)) {
                    console.log(`删除已移除的服务器: ${name}`);
                    await this.deleteConnection(name);
                }
            }
            
            // 添加或更新服务器
            for (const [name, config] of Object.entries(newServers)) {
                const currentConnection = this.connections.find(conn => conn.server.name === name);
                
                // 如果是新服务器或配置已更改，重新连接
                if (!currentConnection) {
                    console.log(`添加新服务器: ${name}`);
                    await this.connectToServer(name, config);
                    
                } else if (JSON.stringify(config) !== currentConnection.server.config) {
                    console.log(`更新服务器配置: ${name}`);
                    
                    // 删除旧连接并创建新连接
                    await this.deleteConnection(name);
                    await this.connectToServer(name, config);
                }
            }
            
            // 通知WebView更新
            console.log('通知WebView更新...');
            await this.notifyWebviewOfServerChanges();
            
        } catch (error) {
            console.error('更新服务器连接失败:', error);
        } finally {
            this.isConnecting = false;
        }
    }
    
    /**
     * 通知WebView服务器变更
     */
    async notifyWebviewOfServerChanges() {
        try {
            if (typeof this.postMessageToWebview === 'function') {
                const servers = this.getServers();
                console.log('向WebView发送服务器列表:', servers);
                await this.postMessageToWebview({
                    type: 'mcpServers',
                    mcpServers: servers
                });
            }
        } catch (error) {
            console.error('通知WebView服务器变更失败:', error);
        }
    }
    
    /**
     * 发送最新服务器列表
     */
    async sendLatestMcpServers() {
        await this.notifyWebviewOfServerChanges();
    }
    
    /**
     * 切换服务器启用/禁用状态
     */
    async toggleServerDisabledRPC(serverName, disabled) {
        try {
            console.log(`切换服务器 ${serverName} 状态为 ${disabled ? '禁用' : '启用'}`);
            
            // 查找连接
            const connection = this.connections.find(conn => conn.server.name === serverName);
            if (!connection) {
                throw new Error(`找不到服务器: ${serverName}`);
            }
            
            // 更新服务器状态
            connection.server.disabled = disabled;
            
            // 读取设置
            const settings = await this.readAndValidateMcpSettingsFile();
            if (!settings) {
                throw new Error('读取MCP设置失败');
            }
            
            // 更新配置
            if (settings.mcpServers[serverName]) {
                settings.mcpServers[serverName].disabled = disabled;
                
                // 保存设置
                const settingsPath = await this.getMcpSettingsFilePath();
                await writeFileContent(settingsPath, JSON.stringify(settings, null, 2));
                
                // 如果禁用了服务器，断开连接
                if (disabled && connection.client) {
                    await this.deleteConnection(serverName);
                    
                    // 重新创建一个禁用状态的连接
                    const config = JSON.parse(connection.server.config);
                    config.disabled = true;
                    
                    // 添加临时连接
                    this.connections.push({
                        server: {
                            name: serverName,
                            config: JSON.stringify(config),
                            status: "disabled",
                            disabled: true,
                            error: "",
                            tools: []
                        },
                        client: null,
                        transport: null
                    });
                    
                } else if (!disabled && !connection.client) {
                    // 如果启用了服务器，建立连接
                    const config = JSON.parse(connection.server.config);
                    config.disabled = false;
                    
                    // 删除旧连接并创建新连接
                    await this.deleteConnection(serverName);
                    await this.connectToServer(serverName, config);
                }
            }
            
            // 通知WebView
            await this.notifyWebviewOfServerChanges();
            
            return this.getServers();
            
        } catch (error) {
            console.error(`切换服务器状态失败: ${serverName}`, error);
            vscode.window.showErrorMessage(`更新服务器状态失败: ${error.message}`);
            throw error;
        }
    }
    
    /**
     * 调用工具
     */
    async callTool(serverName, toolName, toolArguments) {
        try {
            console.log(`调用工具: ${serverName}.${toolName}`, toolArguments);
            
            // 查找连接
            const connection = this.connections.find(conn => conn.server.name === serverName);
            if (!connection) {
                throw new Error(`找不到服务器: ${serverName}`);
            }
            
            // 检查服务器是否禁用
            if (connection.server.disabled) {
                throw new Error(`服务器已禁用: ${serverName}`);
            }
            
            // 检查连接状态
            if (connection.server.status !== 'connected' || !connection.client) {
                throw new Error(`服务器未连接: ${serverName}`);
            }
            
            // 设置超时
            const config = JSON.parse(connection.server.config);
            const timeout = secondsToMs(config.timeout || DEFAULT_MCP_TIMEOUT_SECONDS);
            
            // 调用工具
            const response = await connection.client.request(
                {
                    method: 'tools/call',
                    params: {
                        name: toolName,
                        arguments: toolArguments
                    }
                },
                ExecuteToolResultSchema,  // 使用工具执行结果验证Schema
                { timeout }
            );
            
            return response;
            
        } catch (error) {
            console.error(`调用工具失败: ${serverName}.${toolName}`, error);
            throw error;
        }
    }
    
    /**
     * 切换工具自动批准
     */
    async toggleToolAutoApprove(serverName, toolNames, shouldAllow) {
        try {
            console.log(`切换工具自动批准: ${serverName}`, toolNames, shouldAllow);
            
            // 读取设置
            const settingsPath = await this.getMcpSettingsFilePath();
            const content = await readFileContent(settingsPath);
            const config = JSON.parse(content);
            
            // 确保服务器存在
            if (!config.mcpServers[serverName]) {
                throw new Error(`找不到服务器配置: ${serverName}`);
            }
            
            // 初始化autoApprove数组
            if (!config.mcpServers[serverName].autoApprove) {
                config.mcpServers[serverName].autoApprove = [];
            }
            
            // 获取当前autoApprove列表
            const autoApprove = config.mcpServers[serverName].autoApprove;
            
            // 更新工具自动批准状态
            for (const toolName of toolNames) {
                const index = autoApprove.indexOf(toolName);
                
                if (shouldAllow && index === -1) {
                    // 添加到autoApprove列表
                    autoApprove.push(toolName);
                } else if (!shouldAllow && index !== -1) {
                    // 从autoApprove列表中移除
                    autoApprove.splice(index, 1);
                }
            }
            
            // 保存设置
            await writeFileContent(settingsPath, JSON.stringify(config, null, 2));
            
            // 更新内存中的工具autoApprove状态
            const connection = this.connections.find(conn => conn.server.name === serverName);
            if (connection && connection.server.tools) {
                connection.server.tools = connection.server.tools.map(tool => ({
                    ...tool,
                    autoApprove: autoApprove.includes(tool.name)
                }));
                
                // 通知WebView
                await this.notifyWebviewOfServerChanges();
            }
            
            return this.getServers();
            
        } catch (error) {
            console.error('切换工具自动批准失败:', error);
            vscode.window.showErrorMessage(`更新工具设置失败: ${error.message}`);
            throw error;
        }
    }
    
    /**
     * 添加远程服务器
     */
    async addRemoteServer(serverName, serverUrl) {
        try {
            console.log(`添加远程服务器: ${serverName} ${serverUrl}`);
            
            // 验证URL
            try {
                new URL(serverUrl);
            } catch (error) {
                throw new Error(`无效的URL: ${serverUrl}`);
            }
            
            // 读取设置
            const settings = await this.readAndValidateMcpSettingsFile();
            if (!settings) {
                throw new Error('读取MCP设置失败');
            }
            
            // 检查服务器名称是否已存在
            if (settings.mcpServers[serverName]) {
                throw new Error(`服务器名称已存在: ${serverName}`);
            }
            
            // 创建服务器配置
            const serverConfig = {
                url: serverUrl,
                transportType: ServerConfigTypes.HTTP,
                disabled: false,
                autoApprove: []
            };
            
            // 添加到设置
            settings.mcpServers[serverName] = serverConfig;
            
            // 保存设置
            const settingsPath = await this.getMcpSettingsFilePath();
            await writeFileContent(settingsPath, JSON.stringify(settings, null, 2));
            
            // 连接到新服务器
            await this.connectToServer(serverName, serverConfig);
            
            return this.getServers();
            
        } catch (error) {
            console.error('添加远程服务器失败:', error);
            vscode.window.showErrorMessage(`添加服务器失败: ${error.message}`);
            throw error;
        }
    }
    
    /**
     * 删除服务器
     */
    async deleteServer(serverName) {
        try {
            console.log(`删除服务器: ${serverName}`);
            
            // 读取设置
            const settingsPath = await this.getMcpSettingsFilePath();
            const content = await readFileContent(settingsPath);
            const config = JSON.parse(content);
            
            // 检查服务器是否存在
            if (!config.mcpServers[serverName]) {
                vscode.window.showWarningMessage(`服务器不存在: ${serverName}`);
                return;
            }
            
            // 删除服务器配置
            delete config.mcpServers[serverName];
            
            // 保存设置
            await writeFileContent(settingsPath, JSON.stringify(config, null, 2));
            
            // 删除连接
            await this.deleteConnection(serverName);
            
            // 通知WebView
            await this.notifyWebviewOfServerChanges();
            
            vscode.window.showInformationMessage(`已删除服务器: ${serverName}`);
            
        } catch (error) {
            console.error(`删除服务器失败: ${serverName}`, error);
            vscode.window.showErrorMessage(`删除服务器失败: ${error.message}`);
        }
    }
    
    /**
     * 更新服务器超时设置
     */
    async updateServerTimeoutRPC(serverName, timeout) {
        try {
            console.log(`更新服务器超时设置: ${serverName} ${timeout}秒`);
            
            // 验证超时值
            const timeoutNum = Number(timeout);
            if (isNaN(timeoutNum) || timeoutNum < MIN_MCP_TIMEOUT_SECONDS) {
                throw new Error(`无效的超时值: ${timeout}，最小值为 ${MIN_MCP_TIMEOUT_SECONDS}秒`);
            }
            
            // 读取设置
            const settingsPath = await this.getMcpSettingsFilePath();
            const content = await readFileContent(settingsPath);
            const config = JSON.parse(content);
            
            // 检查服务器是否存在
            if (!config.mcpServers[serverName]) {
                throw new Error(`找不到服务器: ${serverName}`);
            }
            
            // 更新超时设置
            config.mcpServers[serverName].timeout = timeoutNum;
            
            // 保存设置
            await writeFileContent(settingsPath, JSON.stringify(config, null, 2));
            
            // 更新内存中的超时设置
            const connection = this.connections.find(conn => conn.server.name === serverName);
            if (connection) {
                const connConfig = JSON.parse(connection.server.config);
                connConfig.timeout = timeoutNum;
                connection.server.config = JSON.stringify(connConfig);
            }
            
            // 通知WebView
            await this.notifyWebviewOfServerChanges();
            
            return this.getServers();
            
        } catch (error) {
            console.error(`更新服务器超时设置失败: ${serverName}`, error);
            vscode.window.showErrorMessage(`更新超时设置失败: ${error.message}`);
            throw error;
        }
    }
    
    /**
     * 释放资源
     */
    async dispose() {
        try {
            console.log('释放McpHub资源...');
            
            // 清理定时器
            if (this.refreshTimer) {
                clearInterval(this.refreshTimer);
                this.refreshTimer = null;
            }
            
            // 删除所有连接
            for (const connection of [...this.connections]) {
                await this.deleteConnection(connection.server.name);
            }
            
            // 清理文件监视器
            this.removeAllFileWatchers();
            
            // 清理设置文件监视器
            if (this.settingsWatcher) {
                this.settingsWatcher.dispose();
                this.settingsWatcher = null;
            }
            
            // 清理其他资源
            for (const disposable of this.disposables) {
                disposable.dispose();
            }
            this.disposables = [];
            
        } catch (error) {
            console.error('释放McpHub资源失败:', error);
        }
    }
}

module.exports = { McpHub }; 